import { login, logout, getInfo, getUsersRole,getRoles,getUsers, addUser, editUser, deleteUser, resetPassword, } from '@/api/user'
import { getToken, setToken, removeToken } from '@/utils/auth'
import { resetRouter } from '@/router'

const getDefaultState = () => {
  return {
    token: getToken(),
    name: '',
    avatar: '',
    users: [],
    userinfo:[],
    roles:[]
  }
}

const state = getDefaultState()

const mutations = {
  RESET_STATE: (state) => {
    Object.assign(state, getDefaultState())
  },
  SET_TOKEN: (state, token) => {
    state.token = token
  },
  SET_NAME: (state, name) => {
    state.name = name
  },
  SET_AVATAR: (state, avatar) => {
    state.avatar = avatar
  },
  SET_USERS: (state, users) => {
    state.users = users
  },
  SET_USERINFO: (state, user) => {
    state.userinfo = user
  },
  SET_ROLES(state, roles) {
    state.roles = roles;
  },
}

const actions = {
  // 用户登录
  async login({ commit }, userInfo) {
    const { username, password } = userInfo
    try {
      const response = await login({ username: username.trim(), password })
      const { data } = response
      if (data && data.token) {
        commit('SET_TOKEN', data.token)
        setToken(data.token)
      } else {
        throw new Error('登录接口返回数据格式异常，缺少token')
      }
    } catch (error) {
      throw error
    }
  },

  // 获取用户信息
  async getInfo({ commit, state }) {
    try {
      const response = await getInfo(state.token)
      const { data } = response
      if (!data) {
        throw new Error('Verification failed, please Login again.')
      }
      const { name, avatar } = data
      commit('SET_NAME', name)
      commit('SET_AVATAR', avatar)
      return data
    } catch (error) {
      throw error
    }
  },

  // 用户登出
  async logout({ commit, state }) {
    try {
      await logout(state.token)
      removeToken()
      resetRouter()
      commit('RESET_STATE')
    } catch (error) {
      throw error
    }
  },

  // 重置 token（比如退出登录等场景清除状态）
  resetToken({ commit }) {
    removeToken()
    commit('RESET_STATE')
    return Promise.resolve()
  },

  async fetchRoles({ commit }) {
    try {
      const response = await getRoles(); // 替换为您的API路径
      commit('SET_ROLES', response.data);
      console.log("角色信息",response.data);
    } catch (error) {
      throw error;
    } 
  },
  // 获取用户列表
  async loadUsersRole({ commit }) {
    try {
      const response = await getUsersRole()
      commit('SET_USERINFO', response.data)
      return response.data
    } catch (error) {
      throw error
    }
  },
  // 获取用户列表
  async loadUsers({ commit }) {
    try {
      const response = await getUsers()
      commit('SET_USERS', response.data)
      return response.data
    } catch (error) {
      throw error
    }
  },

  // 新增用户
  async addNewUser({ commit }, userData) {
    try {
      const response = await addUser(userData)
      if (response.data.success) {
        // 重新加载用户列表，保持数据最新，可根据实际情况优化此处逻辑，比如只添加新增的用户到列表中
        await this.dispatch('loadUsers')
      }
      return response.data
    } catch (error) {
      throw error
    }
  },

  // 编辑用户
  async editExistingUser({ commit }, userData) {
    console.log("编辑用户", userData);
    try {
      // 分离 id 和其他用户数据
      const { id, ...data } = userData;

      // 调用 API 更新用户信息
      const response = await editUser(id, data);

      if (response.data.success) {
        // 成功后重新加载用户列表，保持数据最新
        // 也可以优化为只更新对应修改的用户信息
        await this.dispatch('loadUsers');
      }
      return response.data;
    } catch (error) {
      throw error;
    }
  },

  // 删除用户
  async deleteUserById({ commit }, userId) {
    try {
      const response = await deleteUser(userId)
      if (response.data.success) {
        // 重新加载用户列表，确保列表数据同步更新
        await this.dispatch('loadUsers')
      }
      return response.data
    } catch (error) {
      throw error
    }
  },

  // 重置用户密码
  async resetUserPassword({ commit }, passwordData) {
    try {
      const response = await resetPassword(passwordData)
      if (response.data.code === 20000) { // 根据后端返回的 code 字段判断
        return response.data;
      } else {
        throw new Error(response.data.message || '服务器返回失败响应');
      }
    } catch (error) {
      throw error
    }
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}